package com.example.jnnews;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;

public class ChangePasswordActivity extends AppCompatActivity {
    private EditText etOldPassword, etNewPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);

        etOldPassword = findViewById(R.id.et_old_password);
        etNewPassword = findViewById(R.id.et_new_password);
        Button btnConfirm = findViewById(R.id.btn_confirm);

        btnConfirm.setOnClickListener(v -> changePassword());
    }

    private void changePassword() {
        String oldPass = etOldPassword.getText().toString();
        String newPass = etNewPassword.getText().toString();
        String username = getIntent().getStringExtra("username");

        if (oldPass.isEmpty() || newPass.isEmpty()) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences prefs = getSharedPreferences("jnnews_prefs", MODE_PRIVATE);
        List<User> users = new Gson().fromJson(
                prefs.getString("users", ""),
                new TypeToken<List<User>>(){}.getType()
        );

        for (User user : users) {
            if (user.getUsername().equals(username)) {
                if (user.getPassword().equals(oldPass)) {
                    user.setPassword(newPass);
                    prefs.edit().putString("users", new Gson().toJson(users)).apply();
                    Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                } else {
                    Toast.makeText(this, "原密码错误", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }
        Toast.makeText(this, "用户不存在", Toast.LENGTH_SHORT).show();
    }
}